// index.js
//获取应用实例
const app = getApp()
  const { formatTime } = require("../../utils/util")
  const{connect}=require("../../utils/mqtt");
  const mqttHost="broker.emqx.io";//mqtt服务器域名
  const mqttPort=8084//mqtt服务器端口

  const deviceSubTopic="/mysmarGejingyuhelloGEJINGYUiosb/sub";//设备订阅topic（小程序发布命令Topic）
  const devicePubTopic="/mysmarGejingyuhelloGEJINGYUiosb/pub";//设备发布topic（小程序订阅数据Topic）

  const mpSubTopic=devicePubTopic
  const mpPubTopic=deviceSubTopic
Page({
  data: {
    client:null,
    Temp:0, 
    humidity:0,
    illumination:0,
    LED:false,
    Beep:false,
    Fan:false
  },
  onLEDChange(event) {
    var that = this;
    console.log(event.detail.value);
    const sw = event.detail.value;
    that.setData({
      LED: sw
    })
    if (sw) {

      that.data.client.publish(mpPubTopic, JSON.stringify({
        target: "LED",
        value: 1
      }), function (err) {
        if (!err) {
          console.log("成功下发命令——开灯");
        }
      });
    } else {
      that.data.client.publish(mpPubTopic, JSON.stringify({
        target: "LED",
        value: 0
      }), function (err) {
        if (!err) {
          console.log("成功下发命令——关灯");
        }
      });
    }
  },

  onBeepChange(event) {
    var that = this;
    console.log(event.detail.value);
    const sw = event.detail.value;
    that.setData({
      Beep: sw
    })
    if (sw) {

      that.data.client.publish(mpPubTopic, JSON.stringify({
        target: "Beep",
        value: 1
      }), function (err) {
        if (!err) {
          console.log("成功下发命令——打开报警器");
        }
      });
    } else {
      that.data.client.publish(mpPubTopic, JSON.stringify({
        target: "Beep",
        value: 0
      }), function (err) {
        if (!err) {
          console.log("成功下发命令——关闭报警器");
        }
      });
    }
  },


  onFanChange(event) {
    var that = this;
    console.log(event.detail.value);
    const sw = event.detail.value;
    that.setData({
      Fan: sw
    })
    if (sw) {

      that.data.client.publish(mpPubTopic, JSON.stringify({
        target: "Fan",
        value: 1
      }), function (err) {
        if (!err) {
          console.log("成功下发命令——打开风扇");
        }
      });
    } else {
      that.data.client.publish(mpPubTopic, JSON.stringify({
        target: "Fan",
        value: 0
      }), function (err) {
        if (!err) {
          console.log("成功下发命令——关闭风扇");
        }
      });
    }
  },

  //事件处理函数
  
  onShow(){
    const that =this
    that.setData({
      //wss 实际上接收wss=》wss实际上就是拥有SSL加密通信的websockect协议
      client:connect(`wxs://${mqttHost}:${mqttPort}/mqtt`)
    })
    that.data.client.on('connect',function(){
      console.log('成功连接到MQTT服务器!');
      wx.showToast({
        title: '连接成功',
        icon:'success',
        mask:true
      })
        that.data.client.subscribe(mpSubTopic,function(err){
              if(!err)
              {
                console.log('成功订阅上行数据Topic')
              }
        })
    })
    that.data.client.on("message",function(topic,message){
      console.log(topic);
      //message是16进制的buffer字节流

      let dataFromeDev={};
      try{
          dataFromeDev=JSON.parse(message);
          console.log(dataFromeDev);
          that.setData({
            Temp:dataFromeDev.Temp,
            humidity:dataFromeDev.humidity,
            illumination:dataFromeDev.illumination,
            LED:dataFromeDev.LED,
            Beep:dataFromeDev.Beep,
            Fan:dataFromeDev.Fan
          })

      }catch(error){
        console.log("JSON解析失败");
      }
      
    })
  },
})
